package com.stoa.floatlib

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.stoa.floatlib.StoaFloatReal.managerMap
import com.stoa.floatlib.constant.StoaFloatConstant
import com.stoa.floatlib.constant.StoaFloatConstant.IS_NORMAL_FLOAT_MODE

class StoaActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
    var startedActivityCounts = 0
    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStarted(activity: Activity) {
        if (startedActivityCounts == 0) {
            managerMap.values.forEach { it.notifyForeground(activity) }
        }
        startedActivityCounts++
    }

    override fun onActivityDestroyed(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityStopped(activity: Activity) {
        startedActivityCounts--
        if (startedActivityCounts == 0) {
            managerMap.values.forEach { it.notifyBackground(activity) }
        }
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
    }

    override fun onActivityResumed(activity: Activity) {
        resumeAndAttachStoaView(activity)
    }

    private fun resumeAndAttachStoaView(activity: Activity) {
        if (IS_NORMAL_FLOAT_MODE && StoaFloatConstant.SHOW_FLOAT) {
            managerMap.values.forEach { it.resumeAndAttachStoaViews(activity) }
        }
    }
}